<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>03绘制矩形</title>
	<style type="text/css">
		#firCan {
			display: block;
			border: 1px solid gold;
			margin: auto;
		}
	</style>
</head>

<body>
	<canvas id="firCan" width="1000" height="500">
		<!--Canvas标签宽高默认值为 300*150-->
		当前浏览器版本过低 不支持 Canvas, 请升级!
		<!-- 
				IE 9+ 及其他浏览器都支持Canvas
				IE 9 以下, 可使用 Google 开发的 ExplorerCanvas 插件
			-->
	</canvas>
</body>
<script type="text/javascript">
	// 1, 获取 canvas标签
	var firCan = document.getElementById("firCan");
	// 2, 获取 2D渲染上下文
	var context = firCan.getContext('2d');
	// 3, 绘制矩形
	context.strokeStyle = "red";
	/*
	 * 描边矩形: strokeRect(x, y, w, h)
	 * 四个参数:
	 * 	x 和 y 		确定矩形左上角点的位置
	 * 	w 和 h		确定矩形的宽和高
	 */
	context.strokeRect(10, 50, 200, 100);

	// context.fillStyle = "#FFD700";
	// 填充矩形: fillRect(x, y, w, h)
	// context.fillRect(300, 50, 200, 100);

	// canvas 添加事件
	// 鼠标摁下并移动
	let startX = 10;
	let startY = 50;
	endX = 0;
	endY = 0;
	let mdX = 0;
	let mdY = 0;
	let canMove = false;

	firCan.onmousedown = function (event) {
		let x = event.offsetX;
		let y = event.offsetY;
		mdX = x;
		mdY = y;
		if (x >= startX && x <= startX + 200 && y >= startY && y <= startY + 100) {
			canMove = true;
			firCan.width = 1000;
			firCan.height = 500;
			context.strokeStyle = "yellow";
			context.strokeRect(startX, startY, 200, 100);
		} else {
			canMove = false;
		}
	}

	firCan.onmouseup = function () {
		if (endX && endY) {
			startX = endX;
			startY = endY;
		}
		canMove = false;
		context.strokeStyle = "red";
		context.strokeRect(startX, startY, 200, 100);
	}

	firCan.onmousemove = function (e) {
		let x = e.offsetX;
		let y = e.offsetY;
		if (canMove) {
			// 方式二: 重置 canvas标签的宽和高
			firCan.width = 1000;
			firCan.height = 500;
			endX = startX + (x - mdX);
			endY = startY + (y - mdY);
			context.strokeStyle = "yellow";
			context.strokeRect(startX + (x - mdX), startY + (y - mdY), 200, 100);
		} else {

		}
	}



</script>

</html>